using UnityEngine;
using DLib.BehaviorTree;
using DLib.BehaviorTree.Tasks;

namespace GuardBuilderDemo.Tasks
{
    /// <summary>
    /// 检查警报任务
    /// 检查是否听到警报
    /// </summary>
    public class CheckAlarmTask : TaskNode
    {
        private GuardBuilderDemoScript guard;

        public CheckAlarmTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override NodeState OnUpdate()
        {
            return guard.isAlarmTriggered ? NodeState.Success : NodeState.Failure;
        }
    }

    /// <summary>
    /// 警戒模式任务
    /// 进入警戒状态
    /// </summary>
    public class AlertModeTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;

        public AlertModeTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
            guard.isOnAlert = true;
            guard.isMoving = false;
        }

        protected override NodeState OnUpdate()
        {
            if (Time.time - startTime >= 2f)
            {
                return NodeState.Success;
            }
            return NodeState.Running;
        }
    }

    /// <summary>
    /// 寻找威胁源任务
    /// 在警戒状态下寻找威胁源
    /// </summary>
    public class SearchThreatTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;

        public SearchThreatTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
        }

        protected override NodeState OnUpdate()
        {
            if (Time.time - startTime >= 3f)
            {
                return NodeState.Success;
            }
            return NodeState.Running;
        }
    }

    /// <summary>
    /// 准备战斗任务
    /// 准备与威胁源战斗
    /// </summary>
    public class PrepareCombatTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;

        public PrepareCombatTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
        }

        protected override NodeState OnUpdate()
        {
            if (Time.time - startTime >= 2f)
            {
                guard.isOnAlert = false;
                return NodeState.Success;
            }
            return NodeState.Running;
        }
    }

    /// <summary>
    /// 休息任务
    /// 守卫停下来休息
    /// </summary>
    public class RestTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;

        public RestTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
            guard.isMoving = false;
        }

        protected override NodeState OnUpdate()
        {
            if (Time.time - startTime >= 3f)
            {
                return NodeState.Success;
            }
            return NodeState.Running;
        }

        protected override void OnStop()
        {
            guard.isMoving = true;
        }

        /// <summary>
        /// 处理休息中断
        /// </summary>
        protected override void OnInterrupt()
        {
            Debug.Log("=== 休息被警报中断！ ===");
            guard.isMoving = true; // 恢复移动状态
        }
    }

    /// <summary>
    /// 聊天任务
    /// 守卫给朋友发信息聊天
    /// </summary>
    public class ChatTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;

        public ChatTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
            guard.isMoving = false;
        }

        protected override NodeState OnUpdate()
        {
            if (Time.time - startTime >= 2f)
            {
                return NodeState.Success;
            }
            return NodeState.Running;
        }

        protected override void OnStop()
        {
            guard.isMoving = true;
        }

        /// <summary>
        /// 处理聊天中断
        /// </summary>
        protected override void OnInterrupt()
        {
            Debug.Log("=== 聊天被警报中断！ ===");
            guard.isMoving = true; // 恢复移动状态
        }
    }

    /// <summary>
    /// 巡逻任务
    /// 守卫在两个哨所之间移动巡逻
    /// </summary>
    public class PatrolTask : TaskNode
    {
        private GuardBuilderDemoScript guard;

        public PatrolTask(GuardBuilderDemoScript guard)
        {
            this.guard = guard;
        }

        protected override void OnStart()
        {
            guard.isMoving = true;
        }

        protected override NodeState OnUpdate()
        {
            return NodeState.Success;
        }

        /// <summary>
        /// 处理巡逻中断
        /// </summary>
        protected override void OnInterrupt()
        {
            Debug.Log("=== 巡逻被警报中断！ ===");
        }
    }

    /// <summary>
    /// 长时间任务
    /// 用于测试Sequence中断的任务
    /// </summary>
    public class LongTask : TaskNode
    {
        private GuardBuilderDemoScript guard;
        private float startTime;
        private float duration;

        public LongTask(GuardBuilderDemoScript guard, float duration = 5f)
        {
            this.guard = guard;
            this.duration = duration;
        }

        protected override void OnStart()
        {
            startTime = Time.time;
            guard.isMoving = false;
            Debug.Log($"开始执行长时间任务，预计持续 {duration} 秒");
        }

        protected override NodeState OnUpdate()
        {
            float elapsed = Time.time - startTime;
            if (elapsed >= duration)
            {
                Debug.Log("长时间任务完成");
                return NodeState.Success;
            }
            return NodeState.Running;
        }

        protected override void OnStop()
        {
            guard.isMoving = true;
        }

        /// <summary>
        /// 处理长时间任务中断
        /// </summary>
        protected override void OnInterrupt()
        {
            Debug.Log("=== 长时间任务被警报中断！ ===");
            guard.isMoving = true; // 恢复移动状态
        }
    }
}

/// <summary>
/// 守卫AI构建器演示脚本
/// 
/// 需求描述：
/// 1. 正常情况下，守卫在两个哨所之间移动巡逻
/// 2. 巡逻过程中有一定概率停下来休息
/// 3. 巡逻过程中有一定概率给朋友发信息聊天
/// 4. 不管什么状态下，只要听到警报，马上就进入警戒状态
/// 5. 警戒状态下会寻找威胁源并准备战斗
/// 
/// 本演示使用BehaviorTreeBuilder来创建行为树
/// 展示构建器模式的优势：代码更清晰、结构更直观
/// </summary>
public class GuardBuilderDemoScript : MonoBehaviour
{
    /// <summary>行为树组件引用</summary>
    public BehaviorTree behaviorTree;
    
    /// <summary>是否听到警报</summary>
    public bool isAlarmTriggered = false;
    
    /// <summary>当前哨所索引（0或1）</summary>
    public int currentPostIndex = 0;
    
    /// <summary>两个哨所的位置</summary>
    public Transform[] guardPosts = new Transform[2];
    
    /// <summary>休息概率（0-1之间）</summary>
    public float restProbability = 0.3f;
    
    /// <summary>聊天概率（0-1之间）</summary>
    public float chatProbability = 0.2f;
    
    /// <summary>巡逻速度</summary>
    public float patrolSpeed = 2f;
    
    /// <summary>是否正在移动</summary>
    public bool isMoving = false;
    
    /// <summary>目标位置</summary>
    private Vector3 targetPosition;
    
    /// <summary>警戒状态</summary>
    public bool isOnAlert = false;

    /// <summary>
    /// Unity Start方法
    /// 初始化守卫AI并使用构建器创建行为树
    /// </summary>
    void Start()
    {
        // 创建行为树实例
        if (behaviorTree == null)
        {
            behaviorTree = new BehaviorTree();
        }

        // 初始化哨所位置
        InitializeGuardPosts();
        
        // 使用构建器创建守卫行为树
        CreateGuardBehaviorTreeWithBuilder();
    }

    /// <summary>
    /// 初始化哨所位置
    /// </summary>
    void InitializeGuardPosts()
    {
        if (guardPosts[0] == null)
        {
            GameObject post1 = new GameObject("GuardPost1");
            post1.transform.position = transform.position + Vector3.left * 5f;
            guardPosts[0] = post1.transform;
        }
        
        if (guardPosts[1] == null)
        {
            GameObject post2 = new GameObject("GuardPost2");
            post2.transform.position = transform.position + Vector3.right * 5f;
            guardPosts[1] = post2.transform;
        }
        
        targetPosition = guardPosts[currentPostIndex].position;
    }

    /// <summary>
    /// 使用构建器创建守卫行为树
    /// 展示构建器模式的链式调用和嵌套结构
    /// </summary>
    void CreateGuardBehaviorTreeWithBuilder()
    {
        Debug.Log("使用构建器创建守卫行为树...");

        // 使用构建器创建复杂的行为树
        // 顶层选择器：每次都会从头到尾运行，优先级高的在前面
        // 第一项：警报处理（最高优先级）
        // 其他项：正常行为（按优先级排序）
        Node rootNode = new BehaviorTreeBuilder()
            .Selector(true)  // 顶层选择器 - 每次从头到尾运行（用于中断机制）
                .Sequence()  // 优先级1：警报处理（最高优先级）
                    .Task(new GuardBuilderDemo.Tasks.CheckAlarmTask(this))  // 检查警报
                    .Log("警报响起！进入警戒状态", 0.5f)
                    .Task(new GuardBuilderDemo.Tasks.AlertModeTask(this))   // 进入警戒模式
                    .Task(new GuardBuilderDemo.Tasks.SearchThreatTask(this)) // 寻找威胁源
                    .Task(new GuardBuilderDemo.Tasks.PrepareCombatTask(this)) // 准备战斗
                .End()
                .Selector()  // 优先级2：正常巡逻行为
                    .Sequence()  // 休息行为
                        .Random(restProbability)  // 30%概率休息
                        .Log("感觉有点累，休息一下", 0.5f)
                        .Task(new GuardBuilderDemo.Tasks.RestTask(this))
                    .End()
                    .Sequence()  // 聊天行为
                        .Random(chatProbability)  // 20%概率聊天
                        .Log("给朋友发个消息", 0.5f)
                        .Task(new GuardBuilderDemo.Tasks.ChatTask(this))
                    .End()
                    .Sequence()  // 巡逻行为（默认）
                        .Log("继续巡逻", 0.5f)
                        .Task(new GuardBuilderDemo.Tasks.PatrolTask(this))
                    .End()
                    .Sequence()  // 测试Sequence中断：长时间任务序列
                        .Log("开始执行复杂任务序列", 0.5f)
                        .Task(new GuardBuilderDemo.Tasks.LongTask(this, 3f))  // 3秒任务
                        .Log("第一个任务完成，开始第二个任务", 0.5f)
                        .Task(new GuardBuilderDemo.Tasks.LongTask(this, 4f))  // 4秒任务
                        .Log("复杂任务序列完成", 0.5f)
                    .End()
                .End()
            .End()
            .Build();

        // 设置根节点
        behaviorTree.SetRoot(rootNode);
    }

    /// <summary>
    /// Unity Update方法
    /// 处理移动逻辑并手动更新行为树
    /// </summary>
    void Update()
    {
        // 处理移动逻辑
        if (isMoving && !isOnAlert)
        {
            MoveToTarget();
        }
        
        // 手动更新行为树
        if (behaviorTree.isRunning && behaviorTree.root != null)
        {
            NodeState state = behaviorTree.root.Evaluate();
            
            if (state != NodeState.Running)
            {
                behaviorTree.isRunning = false;
                string stateText = state == NodeState.Interrupted ? "被中断" : state.ToString();
                Debug.Log($"Guard Builder Demo Behavior Tree completed with state: {stateText}");
            }
        }
    }

    /// <summary>
    /// 移动到目标位置
    /// </summary>
    void MoveToTarget()
    {
        Vector3 direction = (targetPosition - transform.position).normalized;
        transform.position += direction * patrolSpeed * Time.deltaTime;
        
        if (Vector3.Distance(transform.position, targetPosition) < 0.5f)
        {
            isMoving = false;
            currentPostIndex = (currentPostIndex + 1) % 2;
            targetPosition = guardPosts[currentPostIndex].position;
        }
    }

    /// <summary>
    /// 触发警报
    /// </summary>
    public void TriggerAlarm()
    {
        isAlarmTriggered = true;
        isOnAlert = true;
        Debug.Log("警报被触发！");
    }

    /// <summary>
    /// 解除警报
    /// </summary>
    public void ClearAlarm()
    {
        isAlarmTriggered = false;
        isOnAlert = false;
        Debug.Log("警报解除");
    }

    /// <summary>
    /// 测试Sequence中断
    /// </summary>
    public void TestSequenceInterrupt()
    {
        Debug.Log("=== 测试Sequence中断 ===");
        Debug.Log("1. 等待复杂任务序列开始执行...");
        Debug.Log("2. 在任务执行过程中点击'触发警报'按钮");
        Debug.Log("3. 观察Sequence中的任务是否被正确中断");
    }

    /// <summary>
    /// Unity OnGUI方法
    /// 显示守卫状态和控制界面
    /// </summary>
    void OnGUI()
    {
        // 创建GUI区域
        GUILayout.BeginArea(new Rect(10, 10, 400, 350));
        
        // 显示标题
        GUILayout.Label("守卫AI构建器演示", GUI.skin.box);
        
        // 显示状态信息
        GUILayout.Label($"警报状态: {(isAlarmTriggered ? "触发" : "正常")}");
        GUILayout.Label($"警戒状态: {(isOnAlert ? "警戒中" : "正常")}");
        GUILayout.Label($"当前哨所: {currentPostIndex + 1}");
        GUILayout.Label($"正在移动: {isMoving}");
        
        // 显示AI状态，包括中断状态
        NodeState currentState = behaviorTree.GetCurrentState();
        string stateText = currentState == NodeState.Interrupted ? "被中断" : currentState.ToString();
        GUILayout.Label($"AI状态: {stateText}");
        
        GUILayout.Label($"休息概率: {restProbability:P0}");
        GUILayout.Label($"聊天概率: {chatProbability:P0}");
        
        // 控制按钮
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("触发警报"))
        {
            TriggerAlarm();
        }
        if (GUILayout.Button("解除警报"))
        {
            ClearAlarm();
        }
        GUILayout.EndHorizontal();
        
        if (GUILayout.Button("重新开始"))
        {
            behaviorTree.ResetTree();
        }

        if (GUILayout.Button("测试Sequence中断"))
        {
            TestSequenceInterrupt();
        }
        
        // 显示构建器优势说明
        GUILayout.Label("构建器优势:", GUI.skin.box);
        GUILayout.Label("• 代码结构更清晰");
        GUILayout.Label("• 层次关系更直观");
        GUILayout.Label("• 易于修改和扩展");
        
        // 显示中断功能说明
        GUILayout.Label("中断功能:", GUI.skin.box);
        GUILayout.Label("• 顶层选择器每次从头运行");
        GUILayout.Label("• 警报响起时立即中断当前任务");
        GUILayout.Label("• 支持休息、聊天、巡逻任务中断");
        GUILayout.Label("• 支持Sequence中的任务中断");
        
        // 结束GUI区域
        GUILayout.EndArea();
    }
} 